$(() => {
    const user = JSON.parse(sessionStorage.getItem('user'))
    $('#avatarPreview').attr('src', user.avatar)
    $('#nickName').html(user.nickName)
    //获取分类下拉框数据
    $.ajax({
        type: 'get',
        url: '/categories',
        success(res) {
            const html = template('selectTPL', { data: res })
            $('#category').html(html)
        },
        error() {
            alert('获取分类数据失败!')
        }
    })

    //图片上传
    $('#feature').change(function () {
        const formData = new FormData()
        formData.append('avatar', this.files[0])
        $.ajax({
            type: 'post',
            url: '/upload',
            data: formData,
            processData: false,
            contentType: false,
            success(res) {
                $('#preview').prop('src', res[0].avatar)
                $('#hiddenInput').val(res[0].avatar)
            },
            error() {
                alert('上传失败!')
            }
        })

    })

    //添加文章表单提交
    $('#addArticleForm').on('submit', function () {
        const formData = $(this).serialize()
        console.log(formData);
        $.ajax({
            type: 'post',
            url: '/posts',
            data: formData,
            success(res) {
                console.log(res);
                location.href = '/admin/posts.html'
            },
            error() {
                alert('添加文章失败!')
            }
        })
        return false
    })
})